﻿using B.S.BasicData.Api.Read.Application.Command.ShenPi;
using B.S.BasicData.Domian.Entities.shenpi;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.ShenPi
{
    public class ShenPiStateHandler : IRequestHandler<ShenPiStateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LeaveModel> leaveRepo;

        public ShenPiStateHandler(IBaseRepository<LeaveModel>leaveRepo)
        {
            this.leaveRepo = leaveRepo;
        }
        public async Task<ApiResult<int>> Handle(ShenPiStateCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            var leave=leaveRepo.GetAll().Where(x=>x.Id==request.Id && !x.IsDel).FirstOrDefault();
          // Thread.Sleep(1000);
            if (leave == null)
            {
                res.Message = "没有对应的记录";
                res.Code = ApiEnum.File;
                return Task.FromResult(res).Result;
            }
            if(request.ShenpiState==true)
            {
                leave.ShenpiState=true;
                leave.ShenpiReason = null;
            }
            else if(leave.ShenpiState==false)
            {
                if (string.IsNullOrEmpty(request.ShenpiReason))
                {
                    res.Code= ApiEnum.File;
                    res.Message = "请填写原因";
                    return Task.FromResult(res).Result;
                }
                leave.ShenpiState=true;
                leave.ShenpiReason=request.ShenpiReason;
            }
           await leaveRepo.Update(leave);
            res.Code = ApiEnum.Ok;
            res.Message = "审批成功";
            return Task.FromResult(res).Result;
        }
    }
}
